package com.explorati.LeetCode144.preorderTraversal;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @ Author : Weijian_Wang
 * @ Date : Created in 12:14 2020/9/19 0019
 * @ Description ：前序遍历(非递归)
 */
public class Solution1 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    /**
     * 给定一个二叉树，返回它的 前序 遍历。
     */
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if(root == null) {
            return res;
        }

        Stack<TreeNode> stack = new Stack<TreeNode>();

        stack.push(root);
        while(!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            res.add(cur.val);

            if(cur.right != null) {
                stack.push(cur.right);
            }
            if(cur.left != null) {
                stack.push(cur.left);
            }
        }

        return res;
    }
}
